// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.ScanShipment;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.NavSellOrderDetailMapper;
import com.fowo.api.mapper.NavSellOrderPlatformMapper;
import com.fowo.api.mapper.ScanShipmentMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.SysCountryMapper;
import com.fowo.api.model.nav.sell.order.detail.NavSellOrderDetailSearchParamPo;
import com.fowo.api.model.nav.sell.order.platform.NavSellOrderPlatformSearchParamPo;
import com.fowo.api.model.scan.shipment.ScanShipmentExcelPo;
import com.fowo.api.model.scan.shipment.ScanShipmentImportPo;
import com.fowo.api.model.scan.shipment.ScanShipmentItemVo;
import com.fowo.api.model.scan.shipment.ScanShipmentSearchParamPo;
import com.fowo.api.model.scan.shipment.ScanShipmentVo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.sys.country.SysCountryItemVo;
import com.fowo.api.model.sys.country.SysCountrySearchParamPo;
import com.fowo.api.service.NavSellOrderDetailService;
import com.fowo.api.service.NavSellOrderPlatformService;
import com.fowo.api.service.ScanShipmentService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 扫码发货 服务实现类
 * @author 蜂窝蜜造平台 配置人：鹿丙涛，沈友谅
 */
@Service
@Slf4j
@DataObjectType(ScanShipment.class)
@DS("ds24")
public class ScanShipmentServiceImpl
  extends ServiceImpl<ScanShipmentMapper, ScanShipment>
  implements ScanShipmentService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("deliveryCountryCountry", "sc.`country`");
      put("shopInfoShopName", "si.`shop_name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected ScanShipmentService self;

  @Resource
  protected NavSellOrderDetailService navSellOrderDetailService;

  @Resource
  protected NavSellOrderPlatformService navSellOrderPlatformService;

  @Resource
  protected SysCountryMapper sysCountryMapper;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建扫码发货
   * @param model 扫码发货
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(ScanShipmentVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ScanShipment entity = new ScanShipment();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("扫码发货保存失败");
  }

  /**
   * 更新所有子表
   * @param model 扫码发货
   */
  protected void updateAllChilds(ScanShipmentVo model) throws Exception {
    if (model.getProduct() != null) {
      navSellOrderDetailService.saveAllByParentNavSellOrder(
        model.getId(),
        model.getProduct()
      );
    }

    if (model.getPlatform() != null) {
      navSellOrderPlatformService.saveAllByParentNavSellOrder(
        model.getId(),
        model.getPlatform()
      );
    }
  }

  /**
   * 更新扫码发货
   * @param model 扫码发货
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(ScanShipmentVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ScanShipment entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("扫码发货不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "createTime",
      "createUser",
      "id",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新扫码发货（带空值）
   * @param model 扫码发货
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(ScanShipmentVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ScanShipment entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("扫码发货不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(ScanShipment::getAutoIssu, model.getAutoIssu())
      .set(ScanShipment::getBatchId, model.getBatchId())
      .set(ScanShipment::getBoxId, model.getBoxId())
      .set(ScanShipment::getBuyerEmail, model.getBuyerEmail())
      .set(ScanShipment::getBuyerLeaveWord, model.getBuyerLeaveWord())
      .set(ScanShipment::getBuyerName, model.getBuyerName())
      .set(ScanShipment::getCurrency, model.getCurrency())
      .set(ScanShipment::getCutStatus, model.getCutStatus())
      .set(ScanShipment::getDeliveryAddress1, model.getDeliveryAddress1())
      .set(ScanShipment::getDeliveryAddress2, model.getDeliveryAddress2())
      .set(ScanShipment::getDeliveryAddress3, model.getDeliveryAddress3())
      .set(ScanShipment::getDeliveryAddressType, model.getDeliveryAddressType())
      .set(ScanShipment::getDeliveryArea, model.getDeliveryArea())
      .set(ScanShipment::getDeliveryCarrier, model.getDeliveryCarrier())
      .set(ScanShipment::getDeliveryCity, model.getDeliveryCity())
      .set(ScanShipment::getDeliveryCodeOrder, model.getDeliveryCodeOrder())
      .set(ScanShipment::getDeliveryCompany, model.getDeliveryCompany())
      .set(ScanShipment::getDeliveryCountry, model.getDeliveryCountry())
      .set(ScanShipment::getDeliveryHouseNumber, model.getDeliveryHouseNumber())
      .set(ScanShipment::getDeliveryIssuId, model.getDeliveryIssuId())
      .set(ScanShipment::getDeliveryLogistics, model.getDeliveryLogistics())
      .set(
        ScanShipment::getDeliveryLogisticsChannel,
        model.getDeliveryLogisticsChannel()
      )
      .set(
        ScanShipment::getDeliveryLogisticsProvider,
        model.getDeliveryLogisticsProvider()
      )
      .set(ScanShipment::getDeliveryMessage, model.getDeliveryMessage())
      .set(
        ScanShipment::getDeliveryPartnerOrderId,
        model.getDeliveryPartnerOrderId()
      )
      .set(ScanShipment::getDeliveryPhone, model.getDeliveryPhone())
      .set(ScanShipment::getDeliveryProvince, model.getDeliveryProvince())
      .set(
        ScanShipment::getDeliveryRealCurrencyCode,
        model.getDeliveryRealCurrencyCode()
      )
      .set(
        ScanShipment::getDeliveryRealFeeWeight,
        model.getDeliveryRealFeeWeight()
      )
      .set(
        ScanShipment::getDeliveryRealFeeWeightUnit,
        model.getDeliveryRealFeeWeightUnit()
      )
      .set(ScanShipment::getDeliveryRealFreight, model.getDeliveryRealFreight())
      .set(
        ScanShipment::getDeliveryRealQuantity,
        model.getDeliveryRealQuantity()
      )
      .set(
        ScanShipment::getDeliveryRealSizeHeight,
        model.getDeliveryRealSizeHeight()
      )
      .set(
        ScanShipment::getDeliveryRealSizeLength,
        model.getDeliveryRealSizeLength()
      )
      .set(
        ScanShipment::getDeliveryRealSizeUnit,
        model.getDeliveryRealSizeUnit()
      )
      .set(
        ScanShipment::getDeliveryRealSizeWidth,
        model.getDeliveryRealSizeWidth()
      )
      .set(ScanShipment::getDeliveryRealVolume, model.getDeliveryRealVolume())
      .set(
        ScanShipment::getDeliveryRealVolumeUnit,
        model.getDeliveryRealVolumeUnit()
      )
      .set(ScanShipment::getDeliveryRealWeight, model.getDeliveryRealWeight())
      .set(
        ScanShipment::getDeliveryRealWeightUnit,
        model.getDeliveryRealWeightUnit()
      )
      .set(ScanShipment::getDeliveryReceipt, model.getDeliveryReceipt())
      .set(
        ScanShipment::getDeliveryRecipientIdentityNo,
        model.getDeliveryRecipientIdentityNo()
      )
      .set(
        ScanShipment::getDeliveryRecipientTaxNo,
        model.getDeliveryRecipientTaxNo()
      )
      .set(
        ScanShipment::getDeliveryRecipientTaxType,
        model.getDeliveryRecipientTaxType()
      )
      .set(ScanShipment::getDeliveryRemark, model.getDeliveryRemark())
      .set(ScanShipment::getDeliverySenderTaxNo, model.getDeliverySenderTaxNo())
      .set(
        ScanShipment::getDeliverySenderTaxNoType,
        model.getDeliverySenderTaxNoType()
      )
      .set(ScanShipment::getDeliveryStatus, model.getDeliveryStatus())
      .set(
        ScanShipment::getDeliveryThinkFeeWeight,
        model.getDeliveryThinkFeeWeight()
      )
      .set(
        ScanShipment::getDeliveryThinkFeeWeightUnit,
        model.getDeliveryThinkFeeWeightUnit()
      )
      .set(
        ScanShipment::getDeliveryThinkFreight,
        model.getDeliveryThinkFreight()
      )
      .set(
        ScanShipment::getDeliveryThinkSizeHeight,
        model.getDeliveryThinkSizeHeight()
      )
      .set(
        ScanShipment::getDeliveryThinkSizeLength,
        model.getDeliveryThinkSizeLength()
      )
      .set(
        ScanShipment::getDeliveryThinkSizeUnit,
        model.getDeliveryThinkSizeUnit()
      )
      .set(
        ScanShipment::getDeliveryThinkSizeWidth,
        model.getDeliveryThinkSizeWidth()
      )
      .set(ScanShipment::getDeliveryThinkVolume, model.getDeliveryThinkVolume())
      .set(
        ScanShipment::getDeliveryThinkVolumeUnit,
        model.getDeliveryThinkVolumeUnit()
      )
      .set(ScanShipment::getDeliveryThinkWeight, model.getDeliveryThinkWeight())
      .set(
        ScanShipment::getDeliveryThinkWeightUnit,
        model.getDeliveryThinkWeightUnit()
      )
      .set(ScanShipment::getDeliveryTime, model.getDeliveryTime())
      .set(ScanShipment::getDeliveryTrackId, model.getDeliveryTrackId())
      .set(ScanShipment::getDeliveryType, model.getDeliveryType())
      .set(ScanShipment::getDeliveryWarehouse, model.getDeliveryWarehouse())
      .set(
        ScanShipment::getDeliveryWarehouseType,
        model.getDeliveryWarehouseType()
      )
      .set(ScanShipment::getDeliveryWaybillId, model.getDeliveryWaybillId())
      .set(ScanShipment::getDeliveryWaybillNo, model.getDeliveryWaybillNo())
      .set(ScanShipment::getDeliveryWidType, model.getDeliveryWidType())
      .set(ScanShipment::getDeliveryZipCode, model.getDeliveryZipCode())
      .set(ScanShipment::getDistributionStatus, model.getDistributionStatus())
      .set(ScanShipment::getDistributionTime, model.getDistributionTime())
      .set(ScanShipment::getErrorMessage, model.getErrorMessage())
      .set(ScanShipment::getIsTest, model.getIsTest())
      .set(ScanShipment::getIsWeigh, model.getIsWeigh())
      .set(ScanShipment::getIssuActRules, model.getIssuActRules())
      .set(ScanShipment::getIssuCode, model.getIssuCode())
      .set(ScanShipment::getIssuNumber, model.getIssuNumber())
      .set(ScanShipment::getIssuStatus, model.getIssuStatus())
      .set(ScanShipment::getIssuStatusExplain, model.getIssuStatusExplain())
      .set(ScanShipment::getIssuTime, model.getIssuTime())
      .set(ScanShipment::getLastUpdateTime, model.getLastUpdateTime())
      .set(ScanShipment::getLastUpdateUser, model.getLastUpdateUser())
      .set(
        ScanShipment::getLogisticsOrderStatus,
        model.getLogisticsOrderStatus()
      )
      .set(ScanShipment::getNavSellOrderId, model.getNavSellOrderId())
      .set(ScanShipment::getOnlineStatus, model.getOnlineStatus())
      .set(ScanShipment::getOrderId, model.getOrderId())
      .set(ScanShipment::getOriginalOrderId, model.getOriginalOrderId())
      .set(ScanShipment::getPariLike, model.getPariLike())
      .set(ScanShipment::getPaymentWay, model.getPaymentWay())
      .set(ScanShipment::getPickingDeliveryTime, model.getPickingDeliveryTime())
      .set(ScanShipment::getPickingTime, model.getPickingTime())
      .set(ScanShipment::getPlatformOrderId, model.getPlatformOrderId())
      .set(ScanShipment::getPrintFaceStatus, model.getPrintFaceStatus())
      .set(ScanShipment::getPrintOrderStatus, model.getPrintOrderStatus())
      .set(ScanShipment::getProcessTime, model.getProcessTime())
      .set(ScanShipment::getProviderName, model.getProviderName())
      .set(ScanShipment::getRemark, model.getRemark())
      .set(ScanShipment::getShopInfo, model.getShopInfo())
      .set(ScanShipment::getSite, model.getSite())
      .set(ScanShipment::getSolution, model.getSolution())
      .set(ScanShipment::getSource, model.getSource())
      .set(ScanShipment::getSplitType, model.getSplitType())
      .set(ScanShipment::getStatus, model.getStatus())
      .set(ScanShipment::getTag, model.getTag())
      .set(ScanShipment::getTailTime, model.getTailTime())
      .set(ScanShipment::getType, model.getType())
      .set(
        ScanShipment::getWarehouseActInventoryDeductionType,
        model.getWarehouseActInventoryDeductionType()
      )
      .set(ScanShipment::getWmsOrderId, model.getWmsOrderId())
      .set(ScanShipment::getWoNumber, model.getWoNumber())
      .eq(ScanShipment::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(ScanShipmentSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 产品信息(product) 对应的对象
    NavSellOrderDetailSearchParamPo productSearchParam =
      new NavSellOrderDetailSearchParamPo();
    productSearchParam.setDisableDataPremissions(true);
    productSearchParam.setParentNavSellOrderInList(ids);
    NavSellOrderDetailMapper localNavSellOrderDetailMapper = ContextHolder
      .getApplicationContext()
      .getBean(NavSellOrderDetailMapper.class);
    productSearchParam.applySqlSegments();
    List<Long> productIdList = localNavSellOrderDetailMapper.searchIds(
      productSearchParam
    );
    if (!productIdList.isEmpty()) {
      NavSellOrderDetailService localNavSellOrderDetailService = ContextHolder
        .getApplicationContext()
        .getBean(NavSellOrderDetailService.class);
      localNavSellOrderDetailService.batchDelete(productIdList);
    }

    // 处理子表字段 平台信息(platform) 对应的对象
    NavSellOrderPlatformSearchParamPo platformSearchParam =
      new NavSellOrderPlatformSearchParamPo();
    platformSearchParam.setDisableDataPremissions(true);
    platformSearchParam.setParentNavSellOrderInList(ids);
    NavSellOrderPlatformMapper localNavSellOrderPlatformMapper = ContextHolder
      .getApplicationContext()
      .getBean(NavSellOrderPlatformMapper.class);
    platformSearchParam.applySqlSegments();
    List<Long> platformIdList = localNavSellOrderPlatformMapper.searchIds(
      platformSearchParam
    );
    if (!platformIdList.isEmpty()) {
      NavSellOrderPlatformService localNavSellOrderPlatformService =
        ContextHolder
          .getApplicationContext()
          .getBean(NavSellOrderPlatformService.class);
      localNavSellOrderPlatformService.batchDelete(platformIdList);
    }
  }

  /**
   * 删除扫码发货
   * @param id 扫码发货的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除扫码发货
   * @param ids 扫码发货的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<ScanShipmentImportPo> excelToImportRow(
    ScanShipmentImportPo row,
    Integer rowNumber,
    ScanShipmentVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<ScanShipmentImportPo> ir = new ImportRow<ScanShipmentImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<ScanShipmentImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new ScanShipmentVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, ScanShipmentImportPo.class);

    // 一般数据处理
    vo.setBoxId(SheetUtils.tryToLong(row.getBoxId()));
    vo.setDeliveryCarrier(SheetUtils.tryToLong(row.getDeliveryCarrier()));
    vo.setDeliveryLogistics(SheetUtils.tryToLong(row.getDeliveryLogistics()));
    vo.setDeliveryLogisticsChannel(
      SheetUtils.tryToLong(row.getDeliveryLogisticsChannel())
    );
    vo.setDeliveryLogisticsProvider(
      SheetUtils.tryToLong(row.getDeliveryLogisticsProvider())
    );
    vo.setDeliveryRealFeeWeight(
      SheetUtils.tryToDecimal(row.getDeliveryRealFeeWeight())
    );
    vo.setDeliveryRealFreight(
      SheetUtils.tryToDecimal(row.getDeliveryRealFreight())
    );
    vo.setDeliveryRealQuantity(
      SheetUtils.tryToLong(row.getDeliveryRealQuantity())
    );
    vo.setDeliveryRealSizeHeight(
      SheetUtils.tryToDecimal(row.getDeliveryRealSizeHeight())
    );
    vo.setDeliveryRealSizeLength(
      SheetUtils.tryToDecimal(row.getDeliveryRealSizeLength())
    );
    vo.setDeliveryRealSizeWidth(
      SheetUtils.tryToDecimal(row.getDeliveryRealSizeWidth())
    );
    vo.setDeliveryRealVolume(
      SheetUtils.tryToDecimal(row.getDeliveryRealVolume())
    );
    vo.setDeliveryRealWeight(
      SheetUtils.tryToDecimal(row.getDeliveryRealWeight())
    );
    vo.setDeliveryThinkFeeWeight(
      SheetUtils.tryToDecimal(row.getDeliveryThinkFeeWeight())
    );
    vo.setDeliveryThinkFreight(
      SheetUtils.tryToDecimal(row.getDeliveryThinkFreight())
    );
    vo.setDeliveryThinkSizeHeight(
      SheetUtils.tryToDecimal(row.getDeliveryThinkSizeHeight())
    );
    vo.setDeliveryThinkSizeLength(
      SheetUtils.tryToDecimal(row.getDeliveryThinkSizeLength())
    );
    vo.setDeliveryThinkSizeWidth(
      SheetUtils.tryToDecimal(row.getDeliveryThinkSizeWidth())
    );
    vo.setDeliveryThinkVolume(
      SheetUtils.tryToDecimal(row.getDeliveryThinkVolume())
    );
    vo.setDeliveryThinkWeight(
      SheetUtils.tryToDecimal(row.getDeliveryThinkWeight())
    );
    vo.setDeliveryTime(SheetUtils.tryToDateTime(row.getDeliveryTime()));
    vo.setDeliveryWarehouse(SheetUtils.tryToLong(row.getDeliveryWarehouse()));
    vo.setDistributionTime(SheetUtils.tryToDateTime(row.getDistributionTime()));
    vo.setIssuNumber(SheetUtils.tryToLong(row.getIssuNumber()));
    vo.setIssuTime(SheetUtils.tryToDateTime(row.getIssuTime()));
    vo.setNavSellOrderId(SheetUtils.tryToLong(row.getNavSellOrderId()));
    vo.setPickingDeliveryTime(
      SheetUtils.tryToDateTime(row.getPickingDeliveryTime())
    );
    vo.setPickingTime(SheetUtils.tryToDateTime(row.getPickingTime()));
    vo.setProcessTime(SheetUtils.tryToDateTime(row.getProcessTime()));
    vo.setSite(SheetUtils.tryToLong(row.getSite()));
    vo.setTailTime(SheetUtils.tryToDateTime(row.getTailTime()));
    vo.setWmsOrderId(SheetUtils.tryToLong(row.getWmsOrderId()));
    // 处理关联字段“国家/地区”
    if (
      !SheetUtils.isBlank(row.getDeliveryCountryCountry()) &&
      SheetUtils.isBlank(row.getDeliveryCountry())
    ) {
      SysCountrySearchParamPo deliveryCountrySearchParam =
        new SysCountrySearchParamPo();
      deliveryCountrySearchParam.setLimit(2); // 最大只返回二行记录
      deliveryCountrySearchParam.setCountryEq(
        SheetUtils.trim(row.getDeliveryCountryCountry())
      );
      deliveryCountrySearchParam.applySqlSegments();
      List<SysCountryItemVo> deliveryCountryMatches = sysCountryMapper.search(
        deliveryCountrySearchParam
      );
      if (deliveryCountryMatches.size() == 0) {
        ir.addError("deliveryCountryCountry", "未能在国家中找到匹配的数据");
      } else if (deliveryCountryMatches.size() > 1) {
        ir.addError(
          "deliveryCountryCountry",
          "关联不唯一，在国家中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryCountry(deliveryCountryMatches.get(0).getId());
      }
    }
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getShopInfoShopName()) &&
      SheetUtils.isBlank(row.getShopInfo())
    ) {
      ShopInfoSearchParamPo shopInfoSearchParam = new ShopInfoSearchParamPo();
      shopInfoSearchParam.setLimit(2); // 最大只返回二行记录
      shopInfoSearchParam.setShopNameEq(
        SheetUtils.trim(row.getShopInfoShopName())
      );
      shopInfoSearchParam.applySqlSegments();
      List<ShopInfoItemVo> shopInfoMatches = shopInfoMapper.search(
        shopInfoSearchParam
      );
      if (shopInfoMatches.size() == 0) {
        ir.addError("shopInfoShopName", "未能在店铺中找到匹配的数据");
      } else if (shopInfoMatches.size() > 1) {
        ir.addError(
          "shopInfoShopName",
          "关联不唯一，在店铺中找到多个匹配的数据"
        );
      } else {
        vo.setShopInfo(shopInfoMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<ScanShipmentImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<ScanShipmentImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            ScanShipmentImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              ScanShipmentImportPo row,
              AnalysisContext cxt
            ) {
              ScanShipmentVo vo = new ScanShipmentVo();
              ImportRow<ScanShipmentImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<ScanShipmentImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<ScanShipmentImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      ScanShipmentVo vo = new ScanShipmentVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    ScanShipmentSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "deliveryCountry",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ScanShipmentItemVo) r).getDeliveryCountryCountry())
          )
      );
      exportOptions.addFieldMappingOption(
        "shopInfo",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ScanShipmentItemVo) r).getShopInfoShopName())
          )
      );
      exportOptions.addStringFields(
        "autoIssu",
        "batchId",
        "buyerEmail",
        "buyerLeaveWord",
        "buyerName",
        "currency",
        "cutStatus",
        "deliveryAddress1",
        "deliveryAddress2",
        "deliveryAddress3",
        "deliveryAddressType",
        "deliveryArea",
        "deliveryCity",
        "deliveryCodeOrder",
        "deliveryCompany",
        "deliveryCountryCountry",
        "deliveryHouseNumber",
        "deliveryIssuId",
        "deliveryMessage",
        "deliveryPartnerOrderId",
        "deliveryPhone",
        "deliveryProvince",
        "deliveryRealCurrencyCode",
        "deliveryRealFeeWeightUnit",
        "deliveryRealSizeUnit",
        "deliveryRealVolumeUnit",
        "deliveryRealWeightUnit",
        "deliveryReceipt",
        "deliveryRecipientIdentityNo",
        "deliveryRecipientTaxNo",
        "deliveryRecipientTaxType",
        "deliveryRemark",
        "deliverySenderTaxNo",
        "deliverySenderTaxNoType",
        "deliveryStatus",
        "deliveryThinkFeeWeightUnit",
        "deliveryThinkSizeUnit",
        "deliveryThinkVolumeUnit",
        "deliveryThinkWeightUnit",
        "deliveryTrackId",
        "deliveryType",
        "deliveryWarehouseType",
        "deliveryWaybillId",
        "deliveryWaybillNo",
        "deliveryWidType",
        "deliveryZipCode",
        "distributionStatus",
        "errorMessage",
        "isTest",
        "isWeigh",
        "issuActRules",
        "issuCode",
        "issuStatus",
        "issuStatusExplain",
        "logisticsOrderStatus",
        "onlineStatus",
        "orderId",
        "originalOrderId",
        "pariLike",
        "paymentWay",
        "platformOrderId",
        "printFaceStatus",
        "printOrderStatus",
        "providerName",
        "remark",
        "shopInfoShopName",
        "solution",
        "source",
        "splitType",
        "status",
        "tag",
        "type",
        "warehouseActInventoryDeductionType",
        "woNumber"
      );

      String fileName = String.format(
        "扫码发货(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<ScanShipmentExcelPo> items = new ArrayList<ScanShipmentExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<ScanShipmentItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<ScanShipmentItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (ScanShipmentItemVo item : list) {
        ScanShipmentExcelPo excel = new ScanShipmentExcelPo();
        BeanUtils.copyProperties(item, excel);

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "扫码发货(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(ScanShipmentExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过系统单号查询扫码发货主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByOrderId(String orderId) {
    return this.baseMapper.getIdByOrderId(orderId);
  }

  /**
   * 通过系统单号查询扫码发货多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByOrderId(List<String> list) {
    return this.baseMapper.getIdsByOrderId(list);
  }

  /**
   * 通过扫码发货主键查询系统单号
   */
  @Override
  public String getOrderIdById(Long id) {
    return this.baseMapper.getOrderIdById(id);
  }

  /**
   * 通过扫码发货主键查询系统单号列表
   */
  @Override
  public List<String> getOrderIdByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getOrderIdByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("orderId"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 扫码发货的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public ScanShipmentVo getVoById(Long id) throws Exception {
    ScanShipmentVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    NavSellOrderDetailSearchParamPo productSearchParamPo =
      new NavSellOrderDetailSearchParamPo();
    productSearchParamPo.setParentNavSellOrder(id);
    productSearchParamPo.getExtendData().put("queryMode", "sub");
    productSearchParamPo.getExtendData().put("queryParent", "ScanShipment");
    productSearchParamPo.applySqlSegments();
    vo.setProduct(navSellOrderDetailService.search(productSearchParamPo));

    NavSellOrderPlatformSearchParamPo platformSearchParamPo =
      new NavSellOrderPlatformSearchParamPo();
    platformSearchParamPo.setParentNavSellOrder(id);
    platformSearchParamPo.getExtendData().put("queryMode", "sub");
    platformSearchParamPo.getExtendData().put("queryParent", "ScanShipment");
    platformSearchParamPo.applySqlSegments();
    vo.setPlatform(navSellOrderPlatformService.search(platformSearchParamPo));

    return vo;
  }

  /**
   * 分页查询扫码发货
   * @param search 查询条件
   * @return 扫码发货分页查询结果
   */
  @Override
  public Page<ScanShipmentItemVo> pageSearch(ScanShipmentSearchParamPo search) {
    Page<ScanShipmentItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(ScanShipmentItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 扫码发货快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'ScanShipmentOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<ScanShipmentItemVo>> searchOptions(
    ScanShipmentSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询扫码发货
   * @param search 查询条件
   * @return 扫码发货列表查询结果
   */
  @Override
  public List<ScanShipmentItemVo> search(ScanShipmentSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询扫码发货最后更新时间
   * @param search 查询条件
   * @return 扫码发货最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(ScanShipmentSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 一单一件验货
   */
  @Override
  public List<ScanShipmentItemVo> orderOneProduct(
    ScanShipmentSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.orderOneProduct(search);
  }

  /**
   * 一单一件验货分页
   */
  @Override
  public Page<ScanShipmentItemVo> orderOneProductPage(
    ScanShipmentSearchParamPo search
  ) {
    Page<ScanShipmentItemVo> orderOneProductPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return orderOneProductPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return orderOneProductPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    orderOneProductPage =
      this.baseMapper.orderOneProductPage(
          search.toPage(this.baseMapper.orderOneProductCount(search)),
          search
        );
    List<Long> recordIds = orderOneProductPage
      .getRecords()
      .stream()
      .map(ScanShipmentItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return orderOneProductPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return orderOneProductPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    orderOneProductPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return orderOneProductPage;
  }

  /**
   * 查询一单一件验货最后更新时间
   * @param search 查询条件
   * @return 一单一件验货最后更新时间
   */
  @Override
  public Date orderOneProductLastUpdateTime(ScanShipmentSearchParamPo search) {
    return this.baseMapper.orderOneProductLastUpdateTime(search);
  }

  /**
   * 一单多件验货
   */
  @Override
  public List<ScanShipmentItemVo> orderMoreProduct(
    ScanShipmentSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.orderMoreProduct(search);
  }

  /**
   * 一单多件验货分页
   */
  @Override
  public Page<ScanShipmentItemVo> orderMoreProductPage(
    ScanShipmentSearchParamPo search
  ) {
    Page<ScanShipmentItemVo> orderMoreProductPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return orderMoreProductPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return orderMoreProductPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    orderMoreProductPage =
      this.baseMapper.orderMoreProductPage(
          search.toPage(this.baseMapper.orderMoreProductCount(search)),
          search
        );
    List<Long> recordIds = orderMoreProductPage
      .getRecords()
      .stream()
      .map(ScanShipmentItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return orderMoreProductPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return orderMoreProductPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    orderMoreProductPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return orderMoreProductPage;
  }

  /**
   * 查询一单多件验货最后更新时间
   * @param search 查询条件
   * @return 一单多件验货最后更新时间
   */
  @Override
  public Date orderMoreProductLastUpdateTime(ScanShipmentSearchParamPo search) {
    return this.baseMapper.orderMoreProductLastUpdateTime(search);
  }

  /**
   * 称重
   */
  @Override
  public List<ScanShipmentItemVo> weigh(ScanShipmentSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.weigh(search);
  }

  /**
   * 称重分页
   */
  @Override
  public Page<ScanShipmentItemVo> weighPage(ScanShipmentSearchParamPo search) {
    Page<ScanShipmentItemVo> weighPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return weighPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return weighPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    weighPage =
      this.baseMapper.weighPage(
          search.toPage(this.baseMapper.weighCount(search)),
          search
        );
    List<Long> recordIds = weighPage
      .getRecords()
      .stream()
      .map(ScanShipmentItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return weighPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return weighPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    weighPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return weighPage;
  }

  /**
   * 查询称重最后更新时间
   * @param search 查询条件
   * @return 称重最后更新时间
   */
  @Override
  public Date weighLastUpdateTime(ScanShipmentSearchParamPo search) {
    return this.baseMapper.weighLastUpdateTime(search);
  }

  /**
   * 发货
   */
  @Override
  public List<ScanShipmentItemVo> shipment(ScanShipmentSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.shipment(search);
  }

  /**
   * 发货分页
   */
  @Override
  public Page<ScanShipmentItemVo> shipmentPage(
    ScanShipmentSearchParamPo search
  ) {
    Page<ScanShipmentItemVo> shipmentPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return shipmentPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return shipmentPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    shipmentPage =
      this.baseMapper.shipmentPage(
          search.toPage(this.baseMapper.shipmentCount(search)),
          search
        );
    List<Long> recordIds = shipmentPage
      .getRecords()
      .stream()
      .map(ScanShipmentItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return shipmentPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return shipmentPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    shipmentPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return shipmentPage;
  }

  /**
   * 查询发货最后更新时间
   * @param search 查询条件
   * @return 发货最后更新时间
   */
  @Override
  public Date shipmentLastUpdateTime(ScanShipmentSearchParamPo search) {
    return this.baseMapper.shipmentLastUpdateTime(search);
  }
}
